package com.carrentalplatform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.carrentalplatform.model.RentalOrder;
import com.carrentalplatform.service.RentalOrderService;
import com.carrentalplatform.vo.CreateOrderVO;
import com.carrentalplatform.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/order")
public class RentalOrderController {

    @Autowired
    private RentalOrderService rentalOrderService;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public Result<Long> createOrder(@RequestBody CreateOrderVO orderVO) {
        Long orderId = rentalOrderService.createOrder(
                orderVO.getUserId(),
                orderVO.getVehicleId(),
                orderVO.getStartShopId(),
                orderVO.getEndShopId(),
                orderVO.getStartTime(),
                orderVO.getEndTime()
        );
        
        if (orderId == null) {
            return Result.fail("创建订单失败，请检查车辆是否可租");
        }
        
        return Result.success(orderId);
    }

    /**
     * 完成订单
     */
    @PutMapping("/complete/{id}")
    public Result<Void> completeOrder(@PathVariable Long id) {
        boolean success = rentalOrderService.completeOrder(id);
        if (!success) {
            return Result.fail("完成订单失败");
        }
        
        return Result.success();
    }

    /**
     * 取消订单
     */
    @DeleteMapping("/cancel/{id}")
    public Result<Void> cancelOrder(@PathVariable Long id) {
        boolean success = rentalOrderService.cancelOrder(id);
        if (!success) {
            return Result.fail("取消订单失败");
        }
        
        return Result.success();
    }

    /**
     * 查询用户订单列表
     */
    @GetMapping("/user/{userId}")
    public Result<IPage<RentalOrder>> getUserOrders(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        
        IPage<RentalOrder> orderPage = rentalOrderService.getUserOrders(userId, page, size);
        return Result.success(orderPage);
    }

    /**
     * 查询车行订单列表
     */
    @GetMapping("/shop/{shopId}")
    public Result<IPage<RentalOrder>> getShopOrders(
            @PathVariable Long shopId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        
        IPage<RentalOrder> orderPage = rentalOrderService.getShopOrders(shopId, page, size);
        return Result.success(orderPage);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    public Result<RentalOrder> getOrderDetail(@PathVariable Long id) {
        RentalOrder order = rentalOrderService.getById(id);
        if (order == null) {
            return Result.fail("订单不存在");
        }
        
        return Result.success(order);
    }
} 